﻿using System;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Security.Cryptography;
using System.IO;

/// <summary>
/// Summary description for ITNLip
/// </summary>
public class ITNLip
{
    public ITNLip()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    /// <summary>
    /// kiểm tra mã đã có trong cơ sở dữ liệu chưa ?
    /// </summary>
    /// <param name="sql">truyền câu lệnh sql</param>
    /// <returns></returns>
    public static int Getcount(string sql)
    {
        int Counter = 0;
        SqlConnection cn = new SqlConnection();
        SqlCommand cmd = new SqlCommand(sql);
        try
        {
            cn = ConnectionDB.GetConnection();
            cmd.Connection = cn;
            cn.Open();
            Counter = (int)cmd.ExecuteScalar();
        }
        catch
        {
            Counter = 0;
        }
        finally
        {
            cmd.Dispose();
            cn.Close();
        }


        return Counter;
    }
    /// <summary>
    /// Tách một đối tượng thành mảng xâu
    /// </summary>
    /// <param name="obj">Đối tượng xâu</param>
    /// <param name="ch">Mảng kí tự phân cách</param>
    /// <returns></returns>
    public static string[] SplitString(object obj, char[] ch)
    {
        string st = obj.ToString();
        return st.Split(ch);
    }
    /// <summary>
    /// Lấy ngẫu nhiên ID, độ dài 32 kí tự
    /// </summary>
    /// <returns></returns>
    public static string IDRandom()
    {
        RandomNumberGenerator ran = RandomNumberGenerator.Create();
        byte[] ma = new byte[32];
        ran.GetBytes(ma);
        string str = BitConverter.ToString(ma);
        str = str.Replace("-", "");
        return str;
    }
    /// <summary>
    /// Thực hiện câu lệnh Insert, Update , Delete
    /// </summary>
    /// <param name="sql"></param>
    /// <returns></returns>
    public static bool Executesql(string sql)
    {
        SqlConnection cn = new SqlConnection();
        SqlCommand cmd = new SqlCommand();

        //try
        //{
        cn = ConnectionDB.GetConnection();
        cn.Open();
        cmd.CommandText = sql;
        cmd.Connection = cn;
        cmd.ExecuteNonQuery();

        //}
        //catch
        //{
        //    return false;
        //}
        //finally
        //{
        cn.Close();
        cmd.Dispose();
        //}

        return true;

    }
    /// <summary>
    /// Phuong thuc trả về xâu không có sql injection
    /// </summary>
    /// <param name="st"></param>
    /// <returns></returns>
    public static string SqlInjectionOK(string st)
    {
        string st1 = st.ToLower();
        string[] mStr = new string[] { "database", "insert", "update", "delete", "from", "where", "select", "drop", "having", "order by", "group by", "create", "Alter", "function", "Stored Procedure", "in", "not in", "use", "and", "or", "with", "tl", "--", "{", "}", "++", "#", "%", "[", "]", "=", "==", "'", "/", "?", "*", "@", "\\", "(", ")" };
        st = st.Replace("'", "");
        int k = -1;
        for (int i = 0; i < mStr.Length; i++)
        {
            k = st1.IndexOf(mStr[i]);

            if (k != -1)
            {
                st = st.Insert(k, "");
            }
        }

        return st;
    }
    /// <summary>
    /// chuẩn hoá nội dung tin 
    /// </summary>
    /// <param name="values">nội dung đưa vào</param>
    /// <returns>bỏ các ký tự lạ của fck</returns>
    public static string contentstandard(string values)
    {
        values = values.Replace("<!--[if !supportLists]--><!--[endif]-->", "");
        values = values.Replace("<!--[if !supportLists]-->", "");
        values = values.Replace("<*!--[if !suppo*rtLists]-->", "");
        values = values.Replace("<!--[endif]-->", "");
        values = values.Replace("<**!--[if !suppo**rtLists]-->", "");
        values = values.Replace("<![endif]-->", "");
        values = values.Replace("<*!--[endif]-->", "");
        values = values.Replace("<!--[if !supp*ortLists]-->", "");
        values = values.Replace("<!--[if gte mso 9]-->", "");
        values = values.Replace("<!--[if gte mso 10]-->", "");
        return values;
    }
    /// <summary>
    /// lấy dữ liệu khi truyền vào chuỗi sql
    /// </summary>
    /// <param name="sql"></param>
    /// <returns></returns>
    public static string Getdata(string sql)
    {

        string data = "";
        SqlConnection cn = ConnectionDB.GetConnection();
        SqlDataReader dr;
        SqlCommand cmd = new SqlCommand(sql, cn);
        try
        {
            cn.Open();
            dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                data = Convert.ToString(dr.GetString(0));
            }
            dr.Close();
        }
        catch { }
        finally
        {
            cn.Close();
            cmd.Dispose();
        }


        return data;
    }

    /// <summary>
    /// lấy dữ liệu số khi truyền vào chuỗi sql
    /// </summary>
    /// <param name="sql"></param>
    /// <returns></returns>
    public static int GetNum(string sql)
    {
        int data = 0;
        SqlConnection cn = ConnectionDB.GetConnection();

        SqlDataReader dr;
        SqlCommand cmd = new SqlCommand(sql, cn);
        try
        {
            cn.Open();
            dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                data = Convert.ToInt32(dr.GetInt32(0));
            }
            dr.Close();
        }
        catch { }
        finally
        {
            cn.Close();
            cmd.Dispose();
        }

        return data;
    }
    /// <summary>
    /// lấy về số lớn nhất của trường
    /// </summary>
    /// <param name="sql"></param>
    /// <returns></returns>
    public static int GetMax(string sql)
    {
        int Max = 0;
        SqlConnection cn = ConnectionDB.GetConnection();
        cn.Open();
        SqlCommand cmd = new SqlCommand(sql, cn);
        try
        {
            Max = (int)cmd.ExecuteScalar();
        }
        catch { }

        cn.Close();
        cmd.Dispose();
        return Max;
    }
    /// <summary>
    /// sinh mã tự động của nhân viên
    /// </summary>
    /// <returns></returns>
    public static string AutoMaNV()
    {
        SqlConnection cn = ConnectionDB.GetConnection();
        cn.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "AgentSelectMax";
        cmd.Connection = cn;
        cmd.CommandType = CommandType.StoredProcedure;
        SqlParameter paraOut = new SqlParameter("@Result", DbType.Int32);
        paraOut.Direction = ParameterDirection.Output;
        cmd.Parameters.Add(paraOut);
        int Sophieu = 0;
        cmd.ExecuteNonQuery();
        Sophieu = Convert.ToInt32(paraOut.Value);
        string MaPhieuTra = "";
        MaPhieuTra = Convert.ToString(Sophieu) + "";
        if (MaPhieuTra == "")
        {
            MaPhieuTra = "NV1";
        }

        else
        {
            MaPhieuTra = Convert.ToString(Sophieu + 1);
        }

        cn.Close();
        return "NV" + MaPhieuTra;

    }
    /// <summary>
    /// Lấy về dữ liệu chứa vào DataReader
    /// </summary>
    /// <param name="sql"></param>
    /// <returns></returns>

    public static SqlDataReader getDataReader(string sql)
    {
        SqlConnection cn = new SqlConnection();
        SqlCommand cmd = new SqlCommand();
        SqlDataReader dr;
        //try
        //{
        cn = ConnectionDB.GetConnection();
        cn.Open();
        cmd.CommandText = sql;
        cmd.Connection = cn;
        dr = cmd.ExecuteReader();
        return dr;

        //}

        //catch
        //{
        //    return null;
        //}
        //finally
        //{
        cn.Close();
        cmd.Dispose();
        //}

    }
    /// <summary>
    /// Kiem tra du lieu so
    /// </summary>
    /// <param name="st"></param>
    /// <returns></returns>
    public static bool isNumber(string st)
    {
        StringBuilder stb = new StringBuilder(st);
        for (int i = 0; i < stb.Length; i++)
        {
            if (((int)stb[i] < 48) || ((int)stb[i] > 57))
            {
                return false;
                break;
            }
        }
        return true;
    }
    //Hàm xóa file đã bị thay
    public static void DeleteFile(string fileName)
    {
        try
        {
            FileInfo fi;
            if (System.IO.File.Exists(fileName) == true)
            {
                fi = new FileInfo(fileName);
                fi.Delete();
            }
        }
        catch (Exception ex) { ex.Message.ToString(); }
    }

    public static string CatChuoi(string s, int length)
    {
        if (String.IsNullOrEmpty(s))
            throw new ArgumentNullException(s);
        var words = s.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        if (words[0].Length > length)
            return s.Substring(0, length);
        var sb = new StringBuilder();
        foreach (var word in words)
        {
            if ((sb + word).Length > length)
                return string.Format("{0}...", sb.ToString().TrimEnd(' '));
            sb.Append(word + " ");
        }
        return string.Format("{0}...", sb.ToString().TrimEnd(' '));
    }
    private static readonly string[] VietnameseSigns = new string[]

    {
        "aAeEoOuUiIdDyY",

        "áàạảãâấầậẩẫăắằặẳẵ",

        "ÁÀẠẢÃÂẤẦẬẨẪĂẮẰẶẲẴ",

        "éèẹẻẽêếềệểễ",

        "ÉÈẸẺẼÊẾỀỆỂỄ",

        "óòọỏõôốồộổỗơớờợởỡ",

        "ÓÒỌỎÕÔỐỒỘỔỖƠỚỜỢỞỠ",

        "úùụủũưứừựửữ",

        "ÚÙỤỦŨƯỨỪỰỬỮ",

        "íìịỉĩ",

        "ÍÌỊỈĨ",

        "đ",

        "Đ",

        "ýỳỵỷỹ",

        "ÝỲỴỶỸ"
    };

    public static string RemoveSign4VietnameseString(string str)
    {

        //Tiến hành thay thế , lọc bỏ dấu cho chuỗi

        for (int i = 1; i < VietnameseSigns.Length; i++)
        {

            for (int j = 0; j < VietnameseSigns[i].Length; j++)

                str = str.Replace(VietnameseSigns[i][j], VietnameseSigns[0][i - 1]);
        }
        return str;
    }
    public static bool SendMail(string _fromEmail, string toAddress, string subject, string body, string _displayName,
            string strsmtpServer, int intsmtpPort, string struserName, string strpass, bool bolenableSsl)
    {
        bool checkOk = true;
        MailMessage message = new MailMessage();
        message.IsBodyHtml = true;
        string fromAddress = _fromEmail;
        string displayName = _displayName;
        message.From = new MailAddress(fromAddress, displayName);
        message.Subject = subject;
        message.SubjectEncoding = Encoding.UTF8;
        string[] s = toAddress.Split(',');
        for (int i = 0; i < s.Length; i++)
        {
            message.To.Add(new MailAddress(s[i]));
        }
        message.Body = body;
        message.BodyEncoding = Encoding.UTF8;
        string smtpServer = strsmtpServer;
        int smtpPort = intsmtpPort;
        string strEmailAddress = struserName;
        string strEmailPassword = strpass;
        bool enableSsl = bolenableSsl;
        SmtpClient smtp = new SmtpClient();
        smtp.Credentials = new NetworkCredential(strEmailAddress, strEmailPassword);
        smtp.Port = smtpPort;
        smtp.Host = smtpServer;
        smtp.EnableSsl = enableSsl;
        try
        {
            smtp.Send(message);
        }
        catch (Exception ex)
        {
            checkOk = false;
            //logFile.Write("Exception when sending Email: " + ex.Message + " Source:" + ex.Source + " StackTrace:" + ex.StackTrace);
        }
        return checkOk;
    }
}
